import { Component, Input, OnInit } from '@angular/core';
import { SFSchema, SFUISchema } from '@delon/form';
import { NzModalRef, NzMessageService, NzNotificationService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

/**
 * 添加/编辑字典项
 */
@Component({
  selector: 'app-sysdict-item-edit',
  templateUrl: './sysdict-item-edit.component.html',
})
export class SysDictItemEditComponent implements OnInit {
  @Input()
  record: any = {};
  i: any;
  schema: SFSchema = {
    properties: {
      type: { type: 'string', title: '字典key', readOnly: true },
      value: { type: 'string', title: '值' },
      label: { type: 'string', title: '标签名' },
      description: { type: 'string', title: '描述' },
      sort: { type: 'number', title: '排序', default: 1 },
      remarks: { type: 'string', title: '备注' },
    },
    required: ['type', 'value', 'label', 'description'],
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private notice: NzNotificationService,
  ) {}

  ngOnInit(): void {
    if (this.record.id) {
      this.http.get(`/cf/admin/dict/item/${this.record.id}`).subscribe(res => (this.i = res.data));
    }
  }

  save(value: any) {
    const req: Observable<string> = this.record.id
      ? this.http.put('/cf/admin/dict/item', value)
      : this.http.post(`/cf/admin/dict/item`, value);

    req.pipe(catchError(err => of(err))).subscribe(res => {
      if (res.status === 200) {
        this.notice.success('成功', '保存成功');
        this.modal.close(true);
      }
    });
  }

  close() {
    this.modal.destroy();
  }
}
